package beans;

import user.UserAdminManagedBean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import user.User;


/**
 * The LoginManagedBean is used to handle and process all user inputs during the login.
 * The dedicated site is index.xhtml
 * @author Thorsten Ludwig
 */
@ManagedBean(name="loginBean")
@RequestScoped
public class LoginManagedBean {

    /** 
     * Entered Username
     */
    private String name;
    /**
     * Entered Password
     */
    private String password;
    /**
     * Failed the login?. 
     * (due to wrong username/password combination)
     */
    private boolean loginFailed;

    /**
     * create empty Login Bean
     */
    public LoginManagedBean() {
        
    }

    /**
     * Return the current username
     * @return current username
     */
    public String getName() {
        return name;
    }

    /**
     * change the user name
     * @param name new user name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     *  return the users password
     * @return current password
     */
    public String getPw() {
        return password;
    }

    /**
     * change the password
     * @param pw the new pasword
     */
    public void setPw(String pw) {
        this.password = pw;
    }

    /**
     * returns, if the login already failed
     * @return login failed?
     */
    public boolean isLoginFailed() {
        return loginFailed;
    }

    /**
     * change the status, if the login already failed
     * @param loginFailed new status
     */
    public void setLoginFailed(boolean loginFailed) {
        this.loginFailed = loginFailed;
    }
    
    /**
     * Try to login the user.
     * @return "" if the login failed
     *         name of the login page (login.jsf) else
     */
    public String doLogin() {
        FacesContext c = FacesContext.getCurrentInstance();
        UserAdminManagedBean admin = c.getApplication().evaluateExpressionGet(c, "#{userAdminBean}", UserAdminManagedBean.class);
        SessionManagedBean sessionBean = c.getApplication().evaluateExpressionGet(c, "#{sessionBean}", SessionManagedBean.class);
        System.out.println("Try to login");
        String result="";
        if (admin.login (this.name, this.password)) {
            User user = admin.getUser(this.name);
            result = "loggedIn.jsf";
            System.out.println("Login succesful");
            sessionBean.setUser(user);
            sessionBean.init();
        } else {
            this.loginFailed = true;
        }        
        return result;
    }
}
